package mdm.led.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mdm.led.common.AjaxResponse;
import mdm.led.common.Constant;
import mdm.led.common.LocalConfig;
import mdm.led.entity.InspectorList;
import mdm.led.entity.four.FourDatilsParam;
import mdm.led.entity.four.FourDetails;
import mdm.led.entity.four.FourItem;
import mdm.led.service.FourInspectorService;
import mdm.led.util.ListToString;

/**
 *
 * @author :Monarch丿He
 * @date :2018年11月7日
 * @explain :督查四必 App
 */
@Api(description = "督查四必 App")
@RequestMapping("fourInspectorApp")
@Controller
public class FourInspectorAppController {

	private static final Logger LOGGER = LoggerFactory.getLogger(FourInspectorAppController.class);

	@Autowired
	protected LocalConfig localConfig;
	@Autowired
	private FourInspectorService fourInspectorServiceImpl;

	@ApiOperation("查询督查四必部门主列表")
	@RequestMapping(value = "findSectionListInfo", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResponse findSectionListInfo() {

		LOGGER.info("\n--------------- 查询督查四必部门主列表 ---------------");

		List<InspectorList> inspectorList = fourInspectorServiceImpl.findInspectorList("");
		LOGGER.info("\n--------------- 结果:" + inspectorList + " ---------------");
		return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, inspectorList);

	}

	@ApiOperation(value = "督查四必详情列表", notes = "如果是督查角色登录 传入 督查{登录标识(iRet:1为督查角色 2:普通用户),部门id,状态(1:未完成,2:已完成,3:通过,4:未通过),用户名(可选)} ,"
			+ " 如果不是督查角色 需要传入 {用户 id,登录标识(iRet:1为督查角色 2:普通用户),状态(1:未完成,2:已完成,3:通过,4:未通过),用户名(可选)}")
	@RequestMapping(value = "findDetails", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResponse findDetails(@RequestBody FourDatilsParam fourDatilsParam) {
		LOGGER.info("\n--------------- 督查四必详情列表 ---------------");

		List<FourDetails> detailss = fourInspectorServiceImpl.findDetailsApp(fourDatilsParam);
		LOGGER.info("\n--------------- 结果:" + detailss + " ---------------");
		return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, detailss);
	}

	@ApiOperation(value = "根据 督查详情表ID 查询 督查详情表", notes = "需要传入详情表ID")
	@ResponseBody
	@RequestMapping(value = "findDetailsById", method = RequestMethod.GET)
	public AjaxResponse findDetailsById(@RequestParam("detailsId") Integer id) {

		LOGGER.info("\n--------------- 督查四必详情列表 ---------------");

		FourDetails details = fourInspectorServiceImpl.findDetailsById(id);
		LOGGER.info("\n--------------- 结果:" + details + " ---------------");
		return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, details);
	}

	@ApiOperation(value = "填表人填写完成", notes = "传入填表信息 状态传入 2:已完成")
	@ResponseBody
	@RequestMapping(value = "checkComplete", method = RequestMethod.POST)
	public AjaxResponse checkComplete(HttpServletRequest request) {
		LOGGER.info("\n--------------- 填表人填写完成 ---------------");
		// 存放图片的路径
		String imgPath = localConfig.getPicture_upload();

		// {---解析实体---}
		// JSON 字符串
		String body = request.getParameter("body");
		body = body.replaceAll("null","");
		// json 转对象
		FourDetails fourDetails = JSON.parseObject(body, FourDetails.class);
		fourDetails.setWriteTime(new Date());
		// {---解析图片---}
		try {
			Collection<Part> parts = request.getParts();
			// 文件后缀
			String suffix = "";
			// 文件名
			String fileName = "";
			// 图片集合
			List<String> list = new ArrayList<>();
			int i = 0;
			// 循环解析
			for (Part part : parts) {
				if (!part.getName().toString().equals("body")) {
					i++ ;
					fileName = part.getName();
					// 前缀 ---- 检查项 ID
					String prefix = fileName.substring(0, fileName.indexOf("-")+1);
					suffix = fileName.substring(fileName.lastIndexOf("."));
					// 写入文件到 指定文件夹 imgPath
					String file =prefix + String.valueOf(System.currentTimeMillis())+ i + suffix;
					// 添加到 文件集合
					list.add(file);
					// 写入文件
					part.write(imgPath + file);
				}
			}
			List<String> fileStr = null;
			if(fourDetails.getItemList().size() > 0 && list.size() > 0){
				// 循环分类存入图片
				for (FourItem item : fourDetails.getItemList()) {
					fileStr = new ArrayList<>();
					for (String str : list) {
						// 前缀 ---- 检查项 ID
						String prefix = str.substring(0, str.indexOf("-"));
						if (Integer.parseInt(prefix) == item.getFourItmeId()) {
							fileStr.add(str);
						}
					}
					if(fileStr.size() > 0){
						String imgsStr = ListToString.stringListToString(fileStr, ",");
						item.setValue(imgsStr);
					}
				}
			}
			

		} catch (IOException | ServletException e) {
			e.printStackTrace();
		}

		boolean iRet = fourInspectorServiceImpl.checkComplete(fourDetails);
		if (iRet) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, "成功");
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "失败");
		}
	}

	@ApiOperation(value = "督查检查", notes = "所需参数 {详情表ID,状态(3:通过,4:未通过) ,原因 (不通过传入原因)}")
	@ResponseBody
	@RequestMapping(value = "inspectorCheck", method = RequestMethod.POST)
	public AjaxResponse InspectorCheck(@RequestParam("detailsId") Integer detailsId,
			@RequestParam("estate") Integer estate, @RequestParam(value = "cause", required = false) String cause) {
		LOGGER.info("\n--------------- 督查检查 ---------------");
		boolean iRet = fourInspectorServiceImpl.InspectorCheck(detailsId, estate, cause);
		if (iRet) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, "成功");
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "失败");
		}
	}

}
